package grpc

import (
	"context"
	"jihe.common/protos/user_server/proto"
	"strings"
	"user_server/internal/models/d_user"
	"user_server/internal/models/user"
	"user_server/internal/models/user_account"
)

func (s *Server) UserGetUserByIds(c context.Context, in *proto.UserGetUserByIdsReq) (out *proto.UserUsers, err error) {
	out = new(proto.UserUsers)
	userTbl := user.NewModel(s.Pgsql.Get())
	out.List, err = userTbl.GetByUids(in.Uids)
	if err != nil {
		return
	}
	return
}

func (s *Server) UserUpdateUserById(c context.Context, in *proto.UserUser) (out *proto.UserNull, err error) {
	out = new(proto.UserNull)
	userTbl := user.NewModel(s.Pgsql.Get())
	err = userTbl.UpdateByUid(in)
	if err != nil {
		return
	}
	return
}

func (s *Server) UserGetAmount(c context.Context, in *proto.UserAccount) (out *proto.UserAccount, err error) {
	out = new(proto.UserAccount)
	userAccountTbl := user_account.NewModel(s.Pgsql.Get())
	return userAccountTbl.GetByUid(in.Uid)
}

func (s *Server) UpdateUserPhotos(c context.Context, in *proto.UserDUser) (out *proto.UserNull, err error) {
	out = new(proto.UserNull)
	err = d_user.NewModel(s.Pgsql.Get()).UpdatePhotosById(in)
	return
}

func (s *Server) UserAddAmount(c context.Context, in *proto.UserAccount) (out *proto.UserNull, err error) {
	out = new(proto.UserNull)
	db := s.Pgsql.Get()
	userAccountTbl := user_account.NewModel(db)
	if in.TotalAmount <= 0 {
		err = userAccountTbl.AddAmount(in)
		if err != nil {
			return
		}
		return
	}
	err = userAccountTbl.Create(in)
	if err != nil {
		if strings.Contains(err.Error(), "user_account_pk") { //已有就在基础上增加
			err = userAccountTbl.AddAmount(in)
			if err != nil {
				return
			}
			return
		}
		return
	}
	return
}
